package com.hckjsec.oa.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.hckjsec.common.annotation.RepeatSubmit;
import com.hckjsec.common.general.ListStringView;
import com.hckjsec.common.utils.ComUtil;
import com.hckjsec.common.utils.DateUtils;
import com.hckjsec.common.utils.SecurityUtils;
import com.hckjsec.common.utils.StringUtils;
import com.hckjsec.oa.domain.OaDate;
import com.hckjsec.oa.service.IOaDateService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hckjsec.common.annotation.Log;
import com.hckjsec.common.core.controller.BaseController;
import com.hckjsec.common.core.domain.AjaxResult;
import com.hckjsec.common.enums.BusinessType;
import com.hckjsec.oa.domain.OaLegalDate;
import com.hckjsec.oa.service.IOaLegalDateService;
import com.hckjsec.common.utils.poi.ExcelUtil;
import com.hckjsec.common.core.page.TableDataInfo;

/**
 * 公司OA法定假期Controller
 * 
 * @author cyt
 * @date 2021-12-21
 */
@RestController
@RequestMapping("/oa/legal")
public class OaLegalDateController extends BaseController
{
    @Autowired
    private IOaLegalDateService oaLegalDateService;

    @Autowired
    private IOaDateService oaDateService;
    /**
     * 查询公司OA法定假期列表
     */
    @GetMapping("/list")
    public TableDataInfo list(OaLegalDate oaLegalDate)
    {
        startPage();
        List<OaLegalDate> list = oaLegalDateService.selectOaLegalDateList(oaLegalDate);
        return getDataTable(list);
    }

    /**
     * 导出公司OA法定假期列表
     */
    @Log(title = "公司OA法定假期", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(OaLegalDate oaLegalDate)
    {
        List<OaLegalDate> list = oaLegalDateService.selectOaLegalDateList(oaLegalDate);
        ExcelUtil<OaLegalDate> util = new ExcelUtil<OaLegalDate>(OaLegalDate.class);
        return util.exportExcel(list, "date");
    }

    /**
     * 获取公司OA法定假期详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        OaLegalDate oaLegalDate = oaLegalDateService.selectOaLegalDateById(id);
        List<ListStringView> listStringViews = new ArrayList<>();
        String supply = StringUtils.isHcNull(oaLegalDate.getSupply(),"");
        if (!"".equals(supply)){
            String[] supArr = supply.split(",");
            for (int i = 0; i < supArr.length; i++) {
                listStringViews.add(new ListStringView("",supArr[i]));
            }
        }
        oaLegalDate.setSupplyList(listStringViews);
        return AjaxResult.success(oaLegalDate);
    }

    /**
     * 新增公司OA法定假期
     */
    @Log(title = "公司OA法定假期", businessType = BusinessType.INSERT)
    @PostMapping
    @RepeatSubmit
    public AjaxResult add(@RequestBody OaLegalDate oaLegalDate)
    {
//        List<Long> llist = new ArrayList<>();
//        llist.add(2021L);
//        llist.add(2022L);
//        llist.add(2023L);
//        llist.add(2024L);
//        llist.add(2025L);
//        for (Long ayear : llist){
//            oaDateService.initOaDate(ayear);//初始化
//        }
        List<String> verifyList = new ArrayList<>();
        verifyList.add(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,oaLegalDate.getStartDate()));
        verifyList.add(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,oaLegalDate.getEndDate()));
        oaLegalDate.setDeptId(SecurityUtils.getDeptId());
        oaLegalDate.setCreateBy(SecurityUtils.getUsername());
        if (!StringUtils.isEmpty(oaLegalDate.getSupplyList())){
            List<String> vlues = oaLegalDate.getSupplyList().stream().map(ListStringView::getValue).collect(Collectors.toList());
            for (String val : vlues){
                verifyList.add(val);
            }
            oaLegalDate.setSupply(StringUtils.join(vlues, ","));
        }
        if (!ComUtil.isLastStr(verifyList,String.valueOf(oaLegalDate.getLegalYear()))){
            return AjaxResult.error("日期选择不在["+String.valueOf(oaLegalDate.getLegalYear())+"]年内");
        }
        int rows = oaLegalDateService.insertOaLegalDate(oaLegalDate);
        if (rows>0){
            //更改主表配置
            List<String> yesList = new ArrayList<>();
            List<String> noList = new ArrayList<>();
            String  startTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,oaLegalDate.getStartDate());
            String  endTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,oaLegalDate.getEndDate());
            String date ="";
            while (true){
                if("".equals(date)){
                    date=startTime;
                }else{
                    date=DateUtils.getNextDayStr(date);
                }
                yesList.add(date);
                if(date.equals(endTime)){
                    break;
                }
            }
            String findSupply = StringUtils.isHcNull(oaLegalDate.getSupply(), "");
            if (!"".equals(findSupply)){
                String[]  supplyArr = oaLegalDate.getSupply().split(",");
                noList = Arrays.asList(supplyArr);
            }
            if (yesList.size()>0){
                oaDateService.updateOaDateYesFestival(yesList.toArray(new String[yesList.size()]));
            }
            if (noList.size()>0){
                oaDateService.updateOaDateNoFestival(noList.toArray(new String[noList.size()]));
            }
        }
        return toAjax(rows);
    }



    /**
     * 修改公司OA法定假期
     */
    @Log(title = "公司OA法定假期", businessType = BusinessType.UPDATE)
    @PutMapping
    @RepeatSubmit
    public AjaxResult edit(@RequestBody OaLegalDate oaLegalDate)
    {
        oaLegalDate.setUpdateBy(SecurityUtils.getUsername());
        List<String> verifyList = new ArrayList<>();
        verifyList.add(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,oaLegalDate.getStartDate()));
        verifyList.add(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,oaLegalDate.getEndDate()));
        if (!StringUtils.isEmpty(oaLegalDate.getSupplyList())){
            List<String> vlues = oaLegalDate.getSupplyList().stream().map(ListStringView::getValue).collect(Collectors.toList());
            for (String val : vlues){
                verifyList.add(val);
            }
            oaLegalDate.setSupply(StringUtils.join(vlues, ","));
        }else{
            oaLegalDate.setSupply("");
        }
        if (!ComUtil.isLastStr(verifyList,String.valueOf(oaLegalDate.getLegalYear()))){
            return AjaxResult.error("日期选择不在["+String.valueOf(oaLegalDate.getLegalYear())+"]年内");
        }
        //1.修改前先进行恢复，再修改
        List<String> oldList = new ArrayList<>();
        OaLegalDate oldOaLegalDate = oaLegalDateService.selectOaLegalDateById(oaLegalDate.getId());
        String  startOldTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,oldOaLegalDate.getStartDate());
        String  endOldTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,oldOaLegalDate.getEndDate());
        String olddate ="";
        while (true){
            if("".equals(olddate)){
                olddate=startOldTime;
            }else{
                olddate=DateUtils.getNextDayStr(olddate);
            }
            oldList.add(olddate);
            if(olddate.equals(endOldTime)){
                break;
            }
        }
        String oldSupply = StringUtils.isHcNull(oldOaLegalDate.getSupply(), "");
        if (!"".equals(oldSupply)){
            String[]  supplyOldArr = oldOaLegalDate.getSupply().split(",");
            for (int i = 0; i < supplyOldArr.length ; i++) {
                oldList.add(supplyOldArr[i]);
            }
        }
        oaDateService.updateOaDateRecoveryFestival(oldList.toArray(new String[oldList.size()]));
        //2.进行修改
        int rows = oaLegalDateService.updateOaLegalDate(oaLegalDate);
        if (rows>0){
            //3.更改主表配置
            List<String> yesList = new ArrayList<>();
            List<String> noList = new ArrayList<>();
            String  startTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,oaLegalDate.getStartDate());
            String  endTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,oaLegalDate.getEndDate());
            String date ="";
            while (true){
                if("".equals(date)){
                    date=startTime;
                }else{
                    date=DateUtils.getNextDayStr(date);
                }
                yesList.add(date);
                if(date.equals(endTime)){
                    break;
                }
            }
            String findSupply = StringUtils.isHcNull(oaLegalDate.getSupply(), "");
            if (!"".equals(findSupply)){
                String[]  supplyArr = oaLegalDate.getSupply().split(",");
                noList = Arrays.asList(supplyArr);
            }
            if (yesList.size()>0){
                oaDateService.updateOaDateYesFestival(yesList.toArray(new String[yesList.size()]));
            }
            if (noList.size()>0){
                oaDateService.updateOaDateNoFestival(noList.toArray(new String[noList.size()]));
            }
        }
        return toAjax(rows);
    }

    /**
     * 删除公司OA法定假期
     */
    @Log(title = "公司OA法定假期", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        for (int k = 0; k < ids.length; k++) {
            List<String> oldList = new ArrayList<>();
            OaLegalDate oldOaLegalDate = oaLegalDateService.selectOaLegalDateById(ids[k]);
            String  startOldTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,oldOaLegalDate.getStartDate());
            String  endOldTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,oldOaLegalDate.getEndDate());
            String olddate ="";
            while (true){
                if("".equals(olddate)){
                    olddate=startOldTime;
                }else{
                    olddate=DateUtils.getNextDayStr(olddate);
                }
                oldList.add(olddate);
                if(olddate.equals(endOldTime)){
                    break;
                }
            }
            String oldSupply = StringUtils.isHcNull(oldOaLegalDate.getSupply(), "");
            if (!"".equals(oldSupply)){
                String[]  supplyOldArr = oldOaLegalDate.getSupply().split(",");
                for (int i = 0; i < supplyOldArr.length ; i++) {
                    oldList.add(supplyOldArr[i]);
                }
            }
            oaDateService.updateOaDateRecoveryFestival(oldList.toArray(new String[oldList.size()]));
        }
        return toAjax(oaLegalDateService.deleteOaLegalDateByIds(ids));
    }
}
